import {
  getProjectName,
  getWorkOrderDealWithList,
  takeOrder,
  backtrackSubmit,
  workOderAudit
} from '/service/service'
import {
  getContainerHeight
} from '/utils/getDimensionUtil';
const {
  getCurrentStatusMap
} = require('/utils/statusMap')
Page({
  data: {
    searchValue: null,

    countdown: 5, // 倒计时显示值
    autoRefreshInterval: 0,
    pagePath: '',

    refreshIntervalId: null, // 轮询定时器ID
    countdownIntervalId: null, // 倒计时定时器ID
    remainingTime: 3, // 剩余时间（秒），与轮询间隔保持一致
    searchHeight: 0,

    pageNum: 1,
    pageSize: 10,
    total: 0,
    currentTotal: 0,
    list: [],
    hasMore: true,
    windowHeight: 0,
    isLoading: false,
    scrollTop: 0,
    scrollViewHeight: 0,
    showBackTop: false,
    loadLock: false, // 新增加载锁，防止重复加载

    rangeKey: 0,
    fixRange: ['', ''],
    faultLocation: '',
    projectId: '',
    searchContent: {},

    nextPageData: {},
    takeOrderDialogVisible: false,
    backtrackDialogVisible: false,
    footer2: {
      buttons: [{
        text: '取消',
        type: 'default'
      }, {
        text: '确定',
        type: 'primary'
      }],
      layout: 'horizontal',
    },
    backReason: '',
    workOderAuditInfo: {},
    // isViewMore: false
  },
  onLoad() {
    this.initPagePathAndAutoRefresh()
    this.getProjectNameList()
    this.getWindowHeight()
    this.getList()
  },
  onPullDownRefresh() {
    console.log('下拉刷新');
    this.setData({
      pageNum: 1,
      list: [],
      hasMore: true,
      loadLock: false // 重置加载锁
    }, async () => {
      try {
        await this.getList();
      } catch (e) {
        console.error('下拉刷新失败：', e);
      } finally {
        dd.stopPullDownRefresh();
      }
    });
  },
  onPageScroll(e) {
    const {
      scrollTop
    } = e
    const {
      windowHeight,
      scrollViewHeight,
      isLoading,
      hasMore,
      loadLock,
      total,
      list
    } = this.data
    this.setData({
      showBackTop: scrollTop > 300
    });

    // 基本条件判断：如果正在加载、没有更多数据、有加载锁或总数据为0，则不触发
    if (isLoading || !hasMore || loadLock || total === 0) return

    // 剩余高度 = 列表总高度 - 滚动距离 - 窗口高度
    const remainingDistance = scrollViewHeight - scrollTop - windowHeight
    // console.log(`剩余距离: ${remainingDistance}, 列表长度: ${list.length}, 总条数: ${total}`)

    // 当剩余距离小于50px且当前列表长度小于总条数时触发加载
    if (remainingDistance < 50 && list.length < total) {
      this.setData({
        loadLock: true
      }) // 锁定加载

      this.setData({
        pageNum: this.data.pageNum + 1
      }, () => {
        // 确保getList完成后再解锁
        this.getList().finally(() => {
          this.setData({
            loadLock: false
          })
        })
      })
    }

    this.setData({
      scrollTop
    })
  },
  onReady() {
    this.getSearchHeight()
    this.getWrapHeight()
  },
  initPagePathAndAutoRefresh() {
    try {
      // 1.取当前页面路径
      const currentPage = getCurrentPages().at(-1);
      const pagePath = currentPage.route || '';
      this.setData({
        pagePath
      });
      console.log(pagePath)
      // 2. 读取本地存储
      const autoRefreshInterval = my.getStorageSync({
        key: pagePath
      }).data
      console.log(autoRefreshInterval)
      // 3. 校验并设置自动刷新间隔
      if (autoRefreshInterval) {
        this.setData({
          autoRefreshInterval
        }, () => {
          console.log('当前页面自动刷新间隔初始化成功：', this.data.autoRefreshInterval);
          // 若需要初始化轮询，可在此处调用（如 this.polling?.setInterval(autoRefreshInterval)）
        });
      } else {
        console.log('自动刷新配置无效，不初始化：', {
          autoRefreshInterval
        });
      }
    } catch (err) {
      console.error('初始化页面路径与自动刷新失败：', err);
    }
  },
  onShow() {
    this.handleSearch()
  },
  onHide() {
    console.log('onhide')
  },
  onUnload() {
    console.log('onUnload')
    this.clearAllIntervals()
  },
  clearAllIntervals() {
    const {
      refreshIntervalId,
      countdownIntervalId
    } = this.data;
    if (refreshIntervalId) {
      clearInterval(refreshIntervalId);
    }
    if (countdownIntervalId) {
      clearInterval(countdownIntervalId);
    }
    this.setData({
      refreshIntervalId: null,
      countdownIntervalId: null,
      remainingTime: 3
    });
  },
  getProjectNameList() {
    getProjectName().then(res => {
      const nameList = []
      res.forEach(item => {
        if (item && item.projectName)
          nameList.push(item.projectName)
      })
      nameList.unshift('请选择项目')
      this.setData({
        projectNameList: nameList
      });
      // console.log(this.data.projectNameList)
    }).catch(e => {
      console.error(`获取项目名称列表失败：${e}`)
    })
  },
  getWindowHeight() {
    const systemInfo = my.getSystemInfoSync()
    this.setData({
      windowHeight: systemInfo.windowHeight
    })
    console.log('窗口高度:', this.data.windowHeight)
  },
  async getList() {
    if (this.data.isLoading || !this.data.hasMore) return
    const {
      pageNum,
      pageSize,
      searchContent
    } = this.data
    const params = {
      pageNum,
      pageSize,
      ...searchContent
    }
    console.log('请求参数:', params)
    try {
      this.setData({
        isLoading: true
      })
      const res = await getWorkOrderDealWithList(params)
      const {
        rows,
        total
      } = res || {
        rows: [],
        total: 0
      }

      const newList = rows
        .filter(r => !this.data.list.some(old => old.id === r.id))
        .map(item => {
          return {
            ...item,
            currentStatusName: getCurrentStatusMap(item.status),
            isViewMore: false
          }
        })

      const updateList = this.data.list.concat(newList)
      // 调整hasMore判断逻辑：只要当前列表长度小于总条数，就认为还有更多
      const hasMore = updateList.length < total

      console.log(`加载第${pageNum}页，新增${newList.length}条，总${updateList.length}/${total}，是否还有更多: ${hasMore}`)

      this.setData({
        list: updateList,
        total,
        hasMore,
        isLoading: false
      }, () => {
        this.getWrapHeight()
      })
    } catch (e) {
      this.setData({
        isLoading: false,
        loadLock: false // 出错时释放加载锁
      })
      console.log('加载失败:', e)
      my.alert({
        content: '加载失败，请重试'
      })
    }
  },
  async getSearchHeight() {
    const [h1, h2] = await Promise.all([
      getContainerHeight('.search-line-container'),
      getContainerHeight('.refreshControl_container')
    ]);
    const total = h1 + h2;
    if (total) {
      this.setData({
        searchHeight: total
      })
    }
  },
  async getWrapHeight() {
    const scrollViewHeight = await getContainerHeight('.workOrderProcessing_container')
    if (scrollViewHeight) {
      console.log('滚动容器高度:', scrollViewHeight)
      this.setData({
        scrollViewHeight
      })
    }
  },
  backToTop() {
    my.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
    this.setData({
      showBackTop: false
    });
  },
  faultLocationSearchInput(e) {
    this.setData({
      faultLocation: e.detail.value,
      'searchContent.faultLocation': e.detail.value
    })
  },
  projectIdSearchInput(e) {
    this.setData({
      projectId: e.detail.value,
      'searchContent.id': e.detail.value
    })
  },
  onIntervalChange(e) {
    console.log(e)
    const {
      enabled,
      interval
    } = e;
    const {
      pagePath
    } = this.data

    my.setStorageSync({
      key: pagePath,
      data: interval
    })
    this.getSearchHeight()
    console.log(`自动刷新${enabled ? '开启' : '关闭'}，间隔${interval}秒`)
  },
  handleSearch(val) {
    const typeOfVal = typeof val
    if (val === null || typeOfVal === 'string') {
      this.setData({
        searchValue: val
      })
    } 
    const {
      searchValue
    } = this.data

    const searchContent = {
      faultLocation: searchValue
    };

    this.setData({
      list: [],
      searchContent,
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      isLoading: false,
      loadLock: false // 重置加载锁
    }, () => {
      this.getList().then(() => {
        // this.backToTop()
      })
    });
  },
  handleRangeOk(date, format, e) {
    console.log(format)
    this.setData({
      fixRange: format
    })
  },
  handleReset() {
    this.setData({
      rangeKey: this.data.rangeKey + 1,
      fixRange: [],
      projectId: '',
      faultLocation: '',
      searchContent: {},
      list: [],
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      isLoading: false,
      loadLock: false // 重置加载锁
    }, () => {
      this.getList().then(() => {
        this.backToTop()
      });
    });
  },
  viewDetail(e) {
    my.navigateTo({
      url: `/pages/detail/detail?id=${e}`
    })
  },
  takeOrder(e) {
    const {
      id
    } = e.currentTarget.dataset
    this.setData({
      nextPageData: {
        id
      },
      takeOrderDialogVisible: true
    })
  },
  takeOrderDialogConfirm(e) {
    const {
      text
    } = e
    if (text === '确定') {
      const params = {
        workOrderId: this.data.nextPageData.id
      }
      takeOrder(params).then(res => {
        console.log(res)
        if (res && res.code === 200) {
          this.showToast('接单成功')
          this.handleReset()
        } else {
          this.showToast(res.msg, 'fail')
        }
      }).catch(e => {
        this.showToast(e, 'fail')
      })
    }
    this.setData({
      takeOrderDialogVisible: false
    });
  },
  showToast(content = '操作成功', type = 'success', duration = 2000) {
    my.showToast({
      content,
      duration,
      type
    })
  },
  takeOrderDialogClose() {
    this.setData({
      takeOrderDialogVisible: false
    });
  },
  backtrackDialogClose() {
    this.setData({
      back: false
    });
  },
  backtrackDialogConfirm(e) {
    const {
      text
    } = e
    const {
      backReason,
      workOderAuditInfo
    } = this.data
    if (text === '确定') {
      const processedReason = backReason ? backReason.trim() : ''
      if (processedReason !== '') {
        const params = {
          faultDescription: workOderAuditInfo.faultDescription,
          faultLocation: workOderAuditInfo.faultLocation,
          id: workOderAuditInfo.id,
          projectName: workOderAuditInfo.projectName,
          backReason
        }
        backtrackSubmit(params).then(res => {
          if (res.code === 200) {
            this.showToast()
            this.setData({
              backtrackDialogVisible: false
            })
            this.handleReset()
          } else {
            this.showToast(res.msg, 'fail')
          }
        })
      } else {
        this.showToast('请填写退回原因', 'fail')
      }
    } else {
      this.setData({
        backtrackDialogVisible: false
      })
    }
  },
  pageTo(url = '', params = {}, events = {}) {
    const paramKeys = Object.keys(params);

    if (paramKeys.length === 0) {
      my.navigateTo({
        url
      });
      return;
    }

    const queryString = paramKeys.map(key => {
      return `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`;
    }).join('&');

    const fullUrl = `${url}?${queryString}`;
    my.navigateTo({
      url: fullUrl,
      events,
      success: () => {},
      fail: e => {
        console.log(e)
        const {
          errorMessage
        } = e
        if (errorMessage.startsWith('can not find page')) {
          this.showToast('无效页面', 'fail')
        } else {
          this.showToast(errorMessage, 'fail')
        }
      }
    });
  },
  process(e) {
    const {
      id
    } = e.currentTarget.dataset
    this.pageTo('./process/process', {
      id
    })
  },
  async backtrack(e) {

    const {
      id
    } = e.currentTarget.dataset

    try {
      const workOderAuditInfo = await workOderAudit(id)
      if (workOderAuditInfo) {
        this.setData({
          backReason: '',
          nextPageData: {
            id
          },
          backtrackDialogVisible: true,
          workOderAuditInfo
        })
      } else {
        this.showToast('获取工单回退信息失败', 'fail')
      }
    } catch (e) {
      console.error(e)
      this.showToast('获取工单回退信息异常', 'fail')
    }

  },
  backReasonChange(e) {
    // console.log(e)
    this.setData({
      backReason: e
    })
  },
  delay(e) {
    const {
      id
    } = e.currentTarget.dataset
    this.pageTo('./delay/delay', {
      id
    })
  },

  switchMore(e) {
    const {
      id
    } = e.target.dataset
    if (id) {
      const newList = this.data.list.map(item => {
        if (item.id === id) {
          return {
            ...item,
            isViewMore: !item.isViewMore
          };
        }
        return item;
      });
      this.setData({
        list: newList
      });
    }
  },
  copyData(e) {
    const {
      copy
    } = e.target.dataset
    console.log(copy)
    dd.setClipboard({
      text: copy,
    }).then(() => {
      this.showToast('数据已复制')
    });
  }
});